package cn.wolfcode.wolf2w.business.service;

import cn.wolfcode.wolf2w.business.config.DeepSeekProperties;
import cn.wolfcode.wolf2w.business.domain.Strategy;
import cn.wolfcode.wolf2w.business.dto.OpenAIChatRequest;
import cn.wolfcode.wolf2w.business.dto.OpenAIChatResponse;
import cn.wolfcode.wolf2w.business.dto.OpenAIMessage;
import com.alibaba.fastjson2.JSON;
import org.apache.http.client.methods.HttpHead;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@Service
public class DeepseekService {
    @Autowired
    private DeepSeekProperties deepSeekProperties;
    @Autowired
    private RestTemplate restTemplate;

    private final StrategyService strategyService;

    public DeepseekService(StrategyService strategyService) {
        this.strategyService = strategyService;
    }

    //查询deepseek获取结果
    //参数1：用户的基础问题
    //参数2：私库查询回来的数据
    //返回值：deepseek的应答结果
    public String askWithStrategies(String question, List<Strategy> strategies){
        String systemPrompt = buildSystemPrompt(strategies);
        OpenAIMessage systemMessage = new OpenAIMessage("system", systemPrompt);
        OpenAIMessage userMessage = new OpenAIMessage("user", question);
        //要发送给deepseek的消息数据
        List<OpenAIMessage> messages =new ArrayList<>();
        messages.add(systemMessage);
        messages.add(userMessage);

        OpenAIChatRequest requestBody = new OpenAIChatRequest();
        requestBody.setMessages( messages);
        requestBody.setModel(deepSeekProperties.getModel());
        requestBody.setTemperature(0.3);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(deepSeekProperties.getApiKey());

        HttpEntity<OpenAIChatRequest> httpEntity = new HttpEntity<>(requestBody, headers);

        String url=deepSeekProperties.getBaseUrl()+"/chat/completions";
        System.err.println( url);
        /*
        * 请求deepseek的接口
         */
        OpenAIChatResponse response = restTemplate.postForObject(url, httpEntity, OpenAIChatResponse.class);

        if (response == null || response.getChoices() == null || response.getChoices().isEmpty()){
            return "(AI没有找到答案)";
        }
        OpenAIChatResponse.Choice choice = response.getChoices().get(0);
        if (choice== null|| choice.getMessage()==null){
            return "(AI没有找到答案)";
        }
        return choice.getMessage().getContent();

    }

    private String buildSystemPrompt(List<Strategy> strategies) {
        StringJoiner joiner = new StringJoiner("\n\n");
        joiner.add("你是一名知名的导游，请基于提供的私有知识库片段进行回答，形成一篇方法推荐，不要编造。若资料不足请明确说明\n\n" +
                "以下是来自私有知识库的片段（JSON）:");
        for (Strategy strategy : strategies){
            String jsonString = JSON.toJSONString(strategy);
            joiner.add(jsonString);
        }
        return joiner.toString();
    }

}
